package com.fjh.shop.marketing.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjh.shop.common.exceptions.BusinessException;
import com.fjh.shop.common.exceptions.enums.Resp;
import com.fjh.shop.marketing.model.entity.Coupon;
import com.fjh.shop.marketing.service.mapper.CouponMapper;
import com.fjh.shop.marketing.service.service.CouponService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2025-07-16
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Coupon addCoupon(Coupon coupon) {
        // 设置默认值
        if (coupon.getStatus() == null) {
            coupon.setStatus(0); // 默认未使用
        }
        coupon.setCreatedAt(new Date());
        coupon.setUpdatedAt(new Date());

        this.save(coupon);
        return coupon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCoupon(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Coupon updateCoupon(Coupon coupon) {
        if (coupon == null || coupon.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        coupon.setUpdatedAt(new Date());
        this.updateById(coupon);
        return coupon;
    }

    @Override
    public Coupon getCouponById(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.getById(id);
    }

    @Override
    public Page<Coupon> pageCoupon(Integer current, Integer pageSize,
                                 Long id, String name, String startTime,
                                 String endTime, Integer status) {
        LambdaQueryWrapper<Coupon> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(id != null, Coupon::getId, id)
                .like(StringUtils.hasText(name), Coupon::getName, name)
                .ge(StringUtils.hasText(startTime), Coupon::getStartTime, startTime)
                .le(StringUtils.hasText(endTime), Coupon::getEndTime, endTime)
                .eq(status != null, Coupon::getStatus, status);

        // 按创建时间倒序
        queryWrapper.orderByDesc(Coupon::getCreatedAt);

        return this.page(new Page<>(current, pageSize), queryWrapper);
    }
}
